#include <stdio.h>
#include <string.h>

#include <get_history.h>
#include <data.h>

#ifdef TURTLE
#include <method_turtle.h>
#endif

int main(int argc, char *argv[])
{
	DATA data1[MAX_NUM_OF_DATA], data2[MAX_NUM_OF_DATA];
	int datanum, i;
	char quote[200];
	FILE *output;

	if(argc>=2)
		sprintf(quote, "%s", argv[1]);

	memset(data1, 0, sizeof(data1));
	printf("Downloading history...");
	if( GetHistory(quote, data1, &datanum) < 0 )
		return -1;
	
	memcpy(data2, data1, sizeof(data1));
		
	
	
	
	
#ifdef TURTLE
	int i1, i2, i3, i4;
	double d1, d2;
	TurtleType type;
	DATA *data;
	
	for(type=TURTLE_MIN+1; type<TURTLE_MAX; type++)
	{
		printf("Calculating...000%%");
		d1 = 0;
		data = (type==TURTLE_BUY?data1:data2);
		
		for( i1=1; i1<=120; i1++ )
		{
			for( i2=1; i2<=120; i2++ )
			{
				turtle(data, datanum, type, 20, i1, i2);
				d2 = data[0].money+(data[0].close*1000*data[0].have)*(type==TURTLE_BUY?1:-1);
//				printf("Add in %3d day breakout, Clear in %3d day breakout, Average daily incoming = %.0lf / %d = %.0lf\n", i1, i2, d2, (datanum-i1), d2/(datanum-i1));
				if( d2 > d1 )
				{
					d1 = d2;
					i3 = i1;
					i4 = i2;
				}
				printf("\b\b\b\b%3d%%", ((i1-1)*120+i2)*100/(120*120));
			}
		}

		i1 = i3>i4?i3:i4;
		i1 = i1>21?i1:21;

		printf("\r%s: Add when %3d day breakout, Clear when %3d day breakout, Average daily incoming = %.0lf / %d = %.0lf\n", (type==TURTLE_BUY?"Buy ":"Sell"), i3, i4, d1, (datanum-i1), d1/(datanum-i1));
		turtle(data, datanum, type, 20, i3, i4);
	}

	if( (output=fopen(quote, "w")) != NULL )
	{
		fprintf(output, "日期\t開盤\t最高\t最低\t收盤\tTR\tATR"
			"\t持\t產\t增1\t增2\t增3\t增4\t清1\t清2"
			"\t持\t產\t增1\t增2\t增3\t增4\t清1\t清2"
			"\t總"
			"\n");

		for(i=0; i<datanum; i++)
			fprintf(output, "%4d/%02d/%02d\t%.2lf\t%.2lf\t%.2lf\t%.2lf\t%.2lf\t%.2lf"
				"\t%d\t%.0lf\t%.2lf\t%.2lf\t%.2lf\t%.2lf\t%.2lf\t%.2lf"
				"\t%d\t%.0lf\t%.2lf\t%.2lf\t%.2lf\t%.2lf\t%.2lf\t%.2lf"
				"\t%.0lf"
				"\n"
				, data1[i].year, data1[i].month, data1[i].day, data1[i].open, data1[i].high, data1[i].low, data1[i].close, data1[i].tr, data1[i].atr
				, data1[i].have, data1[i].money+(data1[i].close*1000*data1[i].have), data1[i].add1, data1[i].add2, data1[i].add3, data1[i].add4, data1[i].del1, data1[i].del2
				, data2[i].have, data2[i].money-(data2[i].close*1000*data2[i].have), data2[i].add1, data2[i].add2, data2[i].add3, data2[i].add4, data2[i].del1, data2[i].del2
				, data1[i].money+(data1[i].close*1000*data1[i].have) + data2[i].money-(data2[i].close*1000*data2[i].have)
				);
		fclose(output);
	}

#endif

	
	
	
	
	
	
	
	
	
	
	return 0;
}
